/*! BUI - v2.0.0 - 2022-03-13 09:03:17 
Copyright (c): kevin.huang  https://gitee.com/kevin-huang/bui2.0.git (qq:757723114) 
Released under MIT License*/
(function ( global, factory) {
//   "use strict";
	if ( typeof module === "object" && typeof module.exports === "object" ) {
		module.exports = global.document ?
			factory( global, true ) :
			function( w ) {
				if ( !w.document ) {
					throw new Error( "Bui requires a window with a document" );
				}
				return factory( w );
			};
	} else {
		  factory( global );
	}  
})( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
//   "use strict";
  var $B = window["$B"] ?  window["$B"] : {};

var btnHtml = "<button  style='{style}' cmd='{cmd}' id='{id}' class='k_toolbar_button k_box_size btn k_toolbar_button_{cls}'><span>{text}</span></button>";
var disabledCls = "k_toolbar_button_disabled";
var defaultOpts = {
    params: undefined, //用于集成到tree datagrid时 行按钮的数据参数
    methodsObject: 'methodsObject', //事件集合对象
    align: 'left', //对齐方式，默认是left 、center、right
    style: 'normal', // plain / min  / normal /  big
    showText: true, // min 类型可以设置是否显示文字
    subMenuPosition: 'auto', //二级菜单的位置，auto/bottom 两种位置支持
    buttons: [] //请参考buttons
};
class Toolbar extends $B.BaseControl {
    constructor(elObj, opts) {
        super();
        super.setElObj(elObj);
        $B.DomUtils.addClass(this.elObj, "k_toolbar_main k_disabled_selected");
        this.buttonWrap = $B.DomUtils.createEl("<div></div>");
        $B.DomUtils.addClass(this.buttonWrap, "_button_wrap_");
        $B.DomUtils.append(this.elObj, this.buttonWrap);
        this.opts = $B.extendObjectFn(true, {}, defaultOpts, opts);
        if (this.opts.align === 'center') {
            $B.DomUtils.css(this.elObj, { "text-align": "center" });
            $B.DomUtils.css(this.buttonWrap, { "width": "100%" });
        }else if(this.opts.align !== "100%"){
            $B.DomUtils.css(this.buttonWrap, { "float": this.opts.align });
            $B.DomUtils.addClass(this.elObj, "clearfix");
        }
        if( this.opts.align === "100%"){
            this.widthRadio = 100 / this.opts.buttons.length;
        }       
        this.isGroup = Array.isArray(this.opts.buttons[0]);
        for (let i = 0, l = this.opts.buttons.length; i < l; ++i) {
            let opt = this.opts.buttons[i];
            if (this.isGroup) {
                let lastBtn;
                for (let j = 0, jlen = opt.length; j < jlen; ++j) {
                    lastBtn = this._createButtonByopt(opt[j], true, this.opts.style, this.buttonWrap).btn;
                }
                if (i !== l - 1) {
                    $B.DomUtils.css(lastBtn, { "border-right": "1px solid #C1C1C1" });
                }
            } else {
                this._createButtonByopt(opt, false, this.opts.style, this.buttonWrap);
            }
        }
        this.bindEvents(this.buttonWrap);
    }
    bindEvents(eventWrap) {
        $B.DomUtils.click(eventWrap, (e) => {
            var target = e.target;
            if (!$B.DomUtils.hasClass(target, "_button_wrap_")) {
                let nodeName = target.nodeName;
                let el = target;
                if (nodeName !== "BUTTON") {
                    el = target.parentNode;
                }
                if ($B.DomUtils.hasClass(el, disabledCls)) {//禁用状态
                    return;
                }
                if ($B.DomUtils.hasClass(el.parentNode, "k_context_menu_container")) {
                    setTimeout(() => {
                        this.hideSubMenuOnTimer(el.parentNode, 1);
                    });
                }
                this._fireEvent(el);
                return false;//阻止冒泡             
            }
        });
    }
    _getOptById(id) {
        var opt = this._loopGetOptById(id, this.opts.buttons);
        return opt;
    }
    _loopGetOptById(id, buttons) {
        var opt, childrens = [];
        for (let i = 0; i < buttons.length; i++) {
            if (Array.isArray(buttons[i])) {
                opt = this._loopGetOptById(id, buttons[i]);
                if (opt) {
                    break;
                }
            } else {
                if (buttons[i].id === id) {
                    opt = buttons[i];
                    break;
                }
                if (buttons[i].children) {
                    for (let j = 0; j < buttons[i].children.length; j++) {
                        childrens.push(buttons[i].children[j]);
                    }
                }
            }
        }
        if (!opt && childrens.length > 0) {
            opt = this._loopGetOptById(id, childrens);
        }
        return opt;
    }
    _fireEvent(btn) {
        var opt = this._getOptById(btn.id);
        if (opt && opt.click) {
            if ($B.isFunctionFn(opt.click)) {
                opt.click.call(btn, this.opts.params, opt);
            } else if (this.opts.methodsObject) {
                let mOBJ = window[this.opts.methodsObject];
                if (mOBJ) {
                    var fn = mOBJ[opt.click];
                    if ($B.isFunctionFn(fn)) {
                        fn.call(btn, this.opts.params, opt);
                    }
                }
            }
        }
    }
    _createButtonByopt(opt, isGroup, style, buttonWrap) {
        var created = true;
        if (typeof opt.visualable !== 'undefined') {
            created = opt.visualable;
        }
        if (created) {
            return this.createButton(opt, opt.text, isGroup, style, buttonWrap);
        }
    }
    createButton(opt, btnTxt, isGroup, style, buttonWrap) {
        var showText = this.opts.showText;
        if (typeof opt.showText !== "undefined") {
            showText = opt.showText;
        }
        var _this = this,
            bgColor = "",
            fontColor,
            $icon,
            $btn,
            $txtSpan,
            iconColor,
            txt = showText ? btnTxt : '';
        if (!opt.id || opt.id === "") { //生成一个id
            opt.id = $B.getUUID();
        }
        if(this.opts.style === "plain" && opt.color && !opt.fontColor){
            opt.fontColor = opt.color;
        }
        var isIconBtn = false;
        if (typeof showText !== 'undefined' && !showText) {
            if (!opt.iconCls || opt.iconCls === "") {
                opt.iconCls = "fa-mouse-pointer";
            }
            isIconBtn = true;
        }
        var isSubMenu = $B.DomUtils.hasClass(buttonWrap, "k_context_menu_container");
        var isGlobalColor = this.opts.color && this.opts.color !== "";
        var isSelftColor = opt.color && opt.color !== "";
        var isDiyBgColor = isGlobalColor || isSelftColor;
        //自定义背景色
        if (isDiyBgColor) {
            if (isSelftColor) { //优先按钮自身的配置
                bgColor = "background-color:" + opt.color + ";";
            } else {
                bgColor = "background-color:" + this.opts.color + ";";
            }
        }
        //自定义文本/按钮颜色
        var isGllobalFontColor = this.opts.fontColor && this.opts.fontColor !== "";
        var isSelftFontColor = opt.fontColor && opt.fontColor !== "";
        var isDiyFontColor = isGllobalFontColor || isSelftFontColor;
        if (isDiyFontColor) {
            if (isSelftFontColor) {
                fontColor = { "color": opt.fontColor };
            } else {
                fontColor = { "color": this.opts.fontColor };
            }
        }else if(!showText){ 
            if(this.opts.style === "plain" && opt.color){
                fontColor = { "color": opt.color };
                isDiyFontColor = true;
            }
        }
        var html = btnHtml.replace("{cmd}", opt.cmd).replace("{id}", opt.id).replace("{cls}", style).replace("{text}", txt).replace("{style}", bgColor);
        if (this.opts.params) {
            delete this.opts.params.Toolbar;
        }
        $btn = $B.DomUtils.createEl(html);
        if(this.widthRadio){
            $btn.style.width = this.widthRadio + "%";
            $btn.style.padding = "0px 0px";
            $btn.style.margin = "0px 0px";
            $btn.style.borderRadius = "0px";
        }
        $txtSpan = $B.DomUtils.children($btn, "span");
        if (isDiyFontColor) {
            $B.DomUtils.css($txtSpan, fontColor);
        }
        let nowrapCss = { "white-space": "nowrap" };
        $B.DomUtils.css($btn, nowrapCss);
        $B.DomUtils.css($txtSpan, nowrapCss);
        let canBorder = true;
        if (isSubMenu && !isIconBtn) {
            canBorder = false;
        }
        if (canBorder) {
            if (opt.border) {
                $B.DomUtils.css($btn, { "border": opt.border });
            } else if (this.opts.border) {
                $B.DomUtils.css($btn, { "border": this.opts.border });
            }
        }
        if (opt.radius) {
            $B.DomUtils.css($btn, { "border-radius": opt.radius });
        } else if (this.opts.radius) {
            $B.DomUtils.css($btn, { "border-radius": this.opts.radius });
        }
        if (isGroup) {
            $B.DomUtils.css($btn, { "margin-right": 0, "border-radius": 0, "-moz-border-radius": 0, "-webkit-border-radius": 0 });
        }
        if (opt.disabled) {
            $B.DomUtils.addClass($btn, disabledCls);
        }
        if (txt === "") {
            $B.DomUtils.attribute($btn, { "title": opt.text });
        }
        if (opt.iconCls && opt.iconCls !== '') {
            let isPlain = _this.opts.style === 'plain';
            if (isPlain) {
                $B.DomUtils.attribute($btn, { "title": btnTxt });
                $B.DomUtils.css($btn, { "background": "none" });
            }
            let fs = "";
            if (_this.opts.fontSize) {
                fs = "style='font-size:" + _this.opts.fontSize + "px'";
            }
            if (opt.childrens && opt.childrens.length > 0) {
                $B.DomUtils.append($btn, '<i style="padding-left:4px" ' + fs + ' class="fa ' + opt.iconCls + '"></i>&nbsp');
            } else {
                $B.DomUtils.prepend($btn, '<i ' + fs + ' class="fa ' + opt.iconCls + '"></i>&nbsp');
            }
            iconColor = fontColor; //与字体颜色一致
            if (opt.iconColor) {
                iconColor = { "color": opt.iconColor };
            }
            $icon = $B.DomUtils.children($btn, "i");
            if (iconColor) {
                $B.DomUtils.css($icon, iconColor);
            }
            if (isIconBtn) {
                $B.DomUtils.css($icon, { "padding": "0px 0px" });
            } else {
                $B.DomUtils.css($txtSpan, { "padding-left": "5px" });
            }
        }  
        var notPriv = opt.params && opt.params.unAuthor ;
        if (notPriv) {
            $B.DomUtils.addClass($btn, "k_no_privilage_cls");
            $B.DomUtils.addClass($btn, disabledCls);
            $B.DomUtils.attribute($btn, {title:$B.config.unAuthor});
        }
        $B.DomUtils.append(buttonWrap, $btn);
        //当没有指定字体颜色、自动调整图标、文本颜色       
        if (!isDiyFontColor) {
            if (!isSubMenu) {
                let ret = this._autoColor($btn, $txtSpan, $icon, opt);
                iconColor = ret.iconColor;
                bgColor = ret.bgColor;
            }
        }
        this._bindSubMenuEvents($btn);
        if (opt.children) {
            var $i = $B.DomUtils.createEl("<i style='position:relative;font-size:10px;padding-right:-8px;padding-left:5px;top:0.5em;' class='fa fa-ellipsis'></i>");
            if (iconColor) {
                $B.DomUtils.css($i, iconColor);
            }
            $B.DomUtils.append($btn, $i);
        }
        return { btn: $btn, txtSpan: $txtSpan, icon: $icon };
    }
    _autoColor($btn, $txtSpan, $icon, opt) {
        let bgColor = $B.DomUtils.css($btn, "backgroundColor");
        let iconColor;
        bgColor = $B.DomUtils.css($btn, "backgroundColor");
        if ($B.isDeepColor(bgColor)) {
            iconColor = { color: "#ffffff" };
            if ($icon && !opt.iconColor) {
                $B.DomUtils.css($icon, iconColor);
            }
            $B.DomUtils.css($txtSpan, iconColor);
        } else { //应用全局的字体颜色即可
            if ($icon && !opt.iconColor) {
                this.clearFontColor($icon);
            }
            this.clearFontColor($txtSpan);
            iconColor = undefined;
        }
        return { iconColor: iconColor, bgColor: bgColor };
    }
    _createSubChildren(children, el, parentId) {
        var _this = this;
        var body = $B.getBody();
        var domInfo = $B.DomUtils.domInfo(el);
        var btnId = el.id;
        var id = this.id + "_" + btnId;
        var top = domInfo.pageTop;
        var left = domInfo.pageLeft;
        var isBottom = this.opts.subMenuPosition === "bottom";
        var minWidth = "";
        if (isBottom && !parentId) { //如果是底部位置            
            top = top + domInfo.height - 2;
            minWidth = "min-width:" + domInfo.width + "px;";
        } else {
            left = left + domInfo.width - 4;
            top = top + domInfo.height / 2;
        }
        let wrap = $B.DomUtils.children(body, "#" + id);
        if (wrap) {
            $B.DomUtils.detach(wrap);
            $B.DomUtils.css(wrap, { top: -10000, left: -10000, "min-width": domInfo.width + "px" });
            $B.DomUtils.append(body, wrap);
            $B.DomUtils.show(wrap);
            this.autoPosition(wrap, domInfo, { top: top, left: left });
            return wrap;
        }
        wrap = $B.DomUtils.createEl("<div id='" + id + "' style='top:-10000px;left:-10000px;position:absolute;padding:6px 8px;" + minWidth + "' class='k_context_menu_container _button_wrap_ k_box_shadow k_disabled_selected" + this.id + "'></div>");
        $B.DomUtils.propData(wrap, { "forbtnid": btnId });
        if (parentId) {
            $B.DomUtils.propData(wrap, { pid: parentId });
        }
        for (let i = 0; i < children.length; i++) {
            children[i].color = undefined;
            children[i].border = undefined;
            let ret = this._createButtonByopt(children[i], false, "plain", wrap); //只能是简单类型            
            let css = { "display": "block", "margin": "0px 0px 3px 0px", "min-width": "100%" };
            if (!this.opts.showText) {
                css["text-align"] = "center";
            } else {
                css["text-align"] = "left";
                if (!children[i].radius) {
                    css["border-radius"] = "0px";
                }
            }
            $B.DomUtils.css(ret.btn, css);
        }
        $B.DomUtils.append(body, wrap);
        //计算大小，合适的位置
        this.autoPosition(wrap, domInfo, { top: top, left: left });
        if (!this.subWrapEvents) {
            this.subWrapEvents = {
                mouseleave: function (e) {
                    _this.hideSubMenuOnTimer(this);
                },
                mouseenter: function () {
                    clearTimeout(_this.hideSubMenuTimer);
                    clearTimeout(_this.hideButtonSubmenuTimer);
                }
            };
        }
        $B.DomUtils.mouseleave(wrap, this.subWrapEvents.mouseleave);
        $B.DomUtils.mouseenter(wrap, this.subWrapEvents.mouseenter);
        this.bindEvents(wrap);
        return wrap;
    }
    /***自适应位置显示***/
    autoPosition(wrap, elInfo, pos) {
        let pid = $B.DomUtils.propData(wrap, "pid");
        var info = $B.DomUtils.domInfo(wrap);
        var bodyInfo = $B.DomUtils.domInfo(document.body);
        var avibleHeight = bodyInfo.height - elInfo.top;
        var avibleWidth = bodyInfo.width - elInfo.left;
        if (pid) { //非一级菜单
            avibleWidth = avibleWidth - elInfo.width;
        }
        var isBottom = this.opts.subMenuPosition === "bottom";
        if (isBottom) {
            avibleHeight = avibleHeight - elInfo.height - 2;
        } else {
            avibleHeight = avibleHeight - elInfo.height / 2;
            avibleWidth = avibleWidth - elInfo.width - 4;
        }
        var diff = avibleWidth - info.width;
        if (diff < 0) {
            if (isBottom && !pid) {
                pos.left = pos.left + diff - 5;
            } else {
                pos.left = elInfo.pageLeft - info.width;
            }
        }
        diff = avibleHeight - info.height;
        if (diff < 0) {
            pos.top = elInfo.pageTop - info.height;
        }
        $B.DomUtils.css(wrap, pos);
    }
    /***
     * timeout方式隐藏子菜单
     * ***/
    hideSubMenuOnTimer(el, timeout) {
        clearTimeout(this.hideSubMenuTimer);
        var timer = 600;
        if (typeof timeout !== "undefined") {
            timer = timeout;
        }
        this.hideSubMenuTimer = setTimeout(() => {
            let forbtnid = $B.DomUtils.propData(el, "forbtnid");
            if (this.currentActivedBtnId === forbtnid) {
                return false;
            }
            let childrens = $B.DomUtils.children(el, "button");
            for (let i = 0; i < childrens.length; i++) {
                let child = childrens[i];
                if (child._subMenu) {
                    this.hideSubMenu(child);
                }
            }
            var pid = $B.DomUtils.propData(el, "pid");
            if (pid) {
                var pWrap = $B.DomUtils.findbyId(pid);
                if (pWrap) {
                    $B.DomUtils.hide(pWrap, 200);
                }
            }
            $B.DomUtils.hide(el, 260);
        }, timer);
    }
    /**
     * 绑定子菜单按钮的事件
     * ***/
    _bindSubMenuEvents($btn) {
        if (!this.subEvents) {
            var _this = this;
            this.subEvents = {
                mouseenter: function (e) {
                    let target = e.target;
                    let nodeName = target.nodeName;
                    let el = target;
                    if (nodeName !== "BUTTON") {
                        el = target.parentNode;
                    }
                    _this.currentActivedBtnId = el.id;
                    _this.currentEnterBtnId = el.id;
                    var previousAll = $B.DomUtils.previousAll(el);
                    var nextAll = $B.DomUtils.nextAll(el);
                    if (previousAll) {
                        for (let i = 0; i < previousAll.length; i++) {
                            _this.hideSubMenu(previousAll[i]);
                        }
                    }
                    if (nextAll) {
                        for (let i = 0; i < nextAll.length; i++) {
                            _this.hideSubMenu(nextAll[i]);
                        }
                    }                  
                    let opt = _this._getOptById(el.id);
                    if (opt.children && opt.children.length > 0) {
                        var parentNode = el.parentNode;
                        var pid;
                        if ($B.DomUtils.hasClass(parentNode, 'k_context_menu_container')) {
                            pid = parentNode.id;
                        }
                        let subMenu = _this._createSubChildren(opt.children, el, pid);
                        el._subMenu = subMenu;
                    }
                },
                mouseleave: function (e) {
                    _this.currentActivedBtnId = undefined;
                    let target = e.target;
                    let nodeName = target.nodeName;
                    let el = target;
                    if (nodeName !== "BUTTON") {
                        el = target.parentNode;
                    }
                    let parentNode = el.parentNode;
                    if (_this.currentEnterBtnId === el.id && $B.DomUtils.hasClass(parentNode, 'k_context_menu_container')) {
                        _this.currentEnterBtnId = undefined;
                        return;
                    }
                    if (this._subMenu) {
                        clearTimeout(_this.hideButtonSubmenuTimer);
                        _this.hideButtonSubmenuTimer = setTimeout(() => {
                            _this.hideSubMenu(this);
                        }, 500);
                    }
                }
            };
        }
        $B.DomUtils.mouseleave($btn, this.subEvents.mouseleave);
        $B.DomUtils.mouseenter($btn, this.subEvents.mouseenter);
    }
    /**
     * 级联隐藏子菜单
     * ***/
    hideSubMenu(el) {
        if (el._subMenu) {
            //级联关闭            
            $B.DomUtils.hide(el._subMenu, 200);
            let childrens = $B.DomUtils.children(el._subMenu, "button");
            for (let i = 0; i < childrens.length; i++) {
                let child = childrens[i];
                if (child._subMenu) {
                    this.hideSubMenu(child);
                }
            }
            el._subMenu = undefined;
        }
    }
    /**
     * 清理颜色声明，恢复全局颜色
     * ***/
    clearFontColor(el) {
        let style = $B.DomUtils.attribute(el, "style");
        if (style) {
            let styleObj = $B.style2cssObj(style);
            delete styleObj.color;
            style = $B.cssObj2string(styleObj);
            $B.DomUtils.attribute(el, { "style": style });
        }
    }
    /**
    *启用按钮（可以批量启用）
    *args  btnIds=[] //按钮的id数组
    ***/
    enableButtons(args) {
        for (var i = 0, l = args.length; i < l; ++i) {
            let id = args[i];
            let el = $B.DomUtils.children(this.buttonWrap, "#" + id);
            $B.DomUtils.removeClass(el, disabledCls);
        }
    }
    /**
     *禁用按钮（可以批量禁用）
     *args  btnIds=[] //按钮的id数组
     ***/
    disableButtons(args) {
        for (var i = 0, l = args.length; i < l; ++i) {
            let id = args[i];
            let el = $B.DomUtils.children(this.buttonWrap, "#" + id);
            $B.DomUtils.addClass(el, disabledCls);
        }
    }
    /***
     *删除按钮（可以批量删除）
     *args btnIds=[] //按钮的id数组
     ***/
    delButtons(args) {
        for (let i = 0, l = args.length; i < l; ++i) {
            let id = args[i];
            let el = $B.DomUtils.children(this.buttonWrap, "#" + id);
            $B.DomUtils.remove(el);
            let ret = this._removeOpt(id, this.opts.buttons);
            if (ret.length !== this.opts.buttons.length) {
                this.opts.buttons = ret;
            }
        }
    }
    _removeDomByOpt(opt) {
        if (opt.children) {
            for (let i = 0; i < opt.children.length; i++) {
                this._removeDomByOpt(opt.children[i]);
            }
            let domId = this.id + "_" + opt.id;
            var body = $B.getBody();
            var el = $B.DomUtils.children(body, "#" + domId);
            if (el) {
                $B.DomUtils.remove(el);
            }
        }
    }
    _removeOpt(id, btnOpts) {
        var newOpts = [];
        var isFinded = false;
        var nextChilds = [];
        var optDel;
        for (let i = 0; i < btnOpts.length; i++) {
            if (id === btnOpts[i].id) {
                isFinded = true;
                optDel = btnOpts[i];
            } else {
                newOpts.push(btnOpts[i]);
            }
            if (btnOpts[i].children) {
                nextChilds.push(btnOpts[i]);
            }
        }
        if (!isFinded) {
            for (let i = 0; i < nextChilds.length; i++) {
                let ret = this._removeOpt(id, nextChilds[i].children);
                if (ret.length !== nextChilds[i].children) {
                    nextChilds[i].children = ret;
                    break;
                }
            }
        } else {
            this._removeDomByOpt(optDel);
        }
        return newOpts;
    }
    /**
     *添加按钮（可以批量添加）
     *args buttons=[]//按钮的json配置
     ***/
    addButtons(args) {
        for (var i = 0, l = args.length; i < l; ++i) {
            var opt = args[i];
            this.opts.buttons.push(opt);
            this._createButtonByopt(opt, this.isGroup, this.opts.style, this.buttonWrap);
        }
    }
    destroy(excuObjName) {
        //子菜单要关联移除
        var body = $B.getBody();
        $B.DomUtils.removeChilds(body, "." + this.id);
        super.destroy(excuObjName);
    }
}
$B["Toolbar"] = Toolbar; 
 if(!window["$B"] ) {window["$B"] = $B;} 
  return window["$B"] ; 
});
